package control

import (
	"ch05/instructions/base"
	"ch05/rtda"
)

type LOOKUP_SWITCH struct {
	defaultOffset int32
	npairs int32
	mathOffsets []int32
}

func (self *LOOKUP_SWITCH) FetchOperands(reader base.BytecodeReader) {
	reader.SkipPadding()
	self.defaultOffset=reader.ReadInt32()
	self.npairs = reader.ReadInt32()
	self.mathOffsets = reader.ReadInt32s(self.npairs *2)
}

func (self *LOOKUP_SWITCH) Execute (frame rtda.Frame) {
	key := frame.OperandStack().PopInt()
	for i := int32(0); i < self.npairs*2; i += 2 {
		if self.mathOffsets[i] == key {
			offset := self.mathOffsets[i+1]
			base.Branch(frame,int(offset))
			return
		}
	}
	base.Branch(frame,int(self.defaultOffset))
}